BookForm = function(cfg){
	BookForm.superclass.constructor.call(this, cfg);
};
top.Ext.extend(BookForm, top.Ext.form.FormPanel, {
	initComponent: function(){
		top.Ext.apply(this, {
			layout: 'border',
	        baseCls: 'x-plain',
	    	border: true,
	        labelAlign: 'right',
	        labelWidth: 50,
			items: [{
				xtype: 'hidden', name: 'book.id'
			},{
				xtype: 'hidden', name: 'book.typeId'
			},{
				xtype: 'hidden', name: 'book.originalId'
			},{
				xtype:"panel",
				layout:"column",
				region: 'north',
		        baseCls: 'x-plain',
				//autoHeight: true, //ie6支持不好
				height:80,
				border:false,
				margins: '3 0 3 0',
				items:[{
					columnWidth:.5,
	                layout: 'form',
	                border:false,
	    	        baseCls: 'x-plain',
	                items: [{
	                    xtype:'textfield', fieldLabel: '书名',
	                    name: 'book.name', allowBlank:false, anchor:'99%'
	                },{
	                    xtype:'textfield', fieldLabel: '又名',
	                    name: 'book.name2', anchor:'99%'
	                },{
	                    xtype:'textfield', fieldLabel: '作者',
	                    name: 'book.author', anchor:'99%'
	                }]
				},{
					columnWidth:.5,
	                layout: 'form',
	    	        baseCls: 'x-plain',
	                border:false,
	                items: [{
	                    xtype:'textfield', fieldLabel: '类别',
	                    name: 'bookTypeName', allowBlank:false, readOnly: true, anchor:'99%'
	                },{
	                    xtype:'textfield', fieldLabel: '出处',
	                    name: 'book.source', anchor:'99%'
	                },{
	                    xtype:'textfield', fieldLabel: '卷次',
	                    name: 'book.rolls', anchor:'99%'
	                }]
				}]
			},{
		    	xtype:"tabpanel",
		    	region: 'center',
		    	border: false,
				activeTab:0,
				//tabWidth: 100,
				//resizeTabs: true,
				items:[
				    new BookFormTabPanel('作者简介', 'book.aboutAuthor'),
				    new BookFormTabPanel('内容提要', 'book.abstract_'),
				    new BookFormTabPanel('学术特点', 'book.academicFeatures'),
				    new BookFormTabPanel('序跋', 'book.preface'),
				    new BookFormTabPanel('地方志', 'book.chorography'),
				    new BookFormTabPanel('版本与馆藏', 'book.holdings'),
				    new BookFormTabPanel('按语', 'book.comment')
				]
			}]
		});
		BookForm.superclass.initComponent.call(this);
	},
	fillData: function(values){
		this.getForm().setValues(values);
	},
	firstFocus: function(){
		this.getForm().findField('book.name').focus(false, 500);
	}
});

BookWin = function(cfg){
	BookWin.superclass.constructor.call(this, cfg);
};
top.Ext.extend(BookWin, top.Ext.Window, {
	initComponent: function(){
		top.Ext.apply(this, {
		    width: MyUtils.getWinWidth(800),
		    height: MyUtils.getWinHeight(600),
		    layout: 'fit',
		    plain:true,
		    modal: true,
		    bodyStyle:'padding:1px;',
		    iconCls: 'icon-window',
		    buttonAlign:'right',
		    items: new BookForm({win: this}),
		    listeners: {
		    	beforeshow: function(){ //填充表单，设置焦点
		    		this.fillForm();
		    		this.firstFocus();
		    	}
		    },
		    buttons: [{
		        text: '从原文分析',
		        handler: function(){new OriginalWin(this).show();},
		        scope: this
		    },{
		        text: '保存',
		        handler: this.submitForm,
		        iconCls: 'icon-save',
		        scope: this
		    },{
		        text: '关闭',
		        handler: this.close,
		        iconCls: 'icon-close',
		        scope: this
		    }]
		});
		BookWin.superclass.initComponent.call(this);
	},
	fillForm: function(){
		var formPanel = this.getForm();
		if (this.bookId){ //修改书籍，从服务器读取数据填充表单
			var url = String.format('book!get.action?bookId={0}', this.bookId);
			MyUtils.getJson(url, true, function(data){
				formPanel.fillData(MyUtils.toFormValues(data.book, 'book.'));
				formPanel.fillData([{id:'bookTypeName', value:data.type.name}]);
			});
		}
		else{//添加书籍时设置类别
			var typeNode = bookMgr.getCurBookType();
			formPanel.fillData([{id:'book.typeId', value:typeNode.id}]);
			formPanel.fillData([{id:'bookTypeName', value:typeNode.text}]);
		}
	},
	submitForm: function(){
		saveBook(this.getForm());
	},
	fillDataFormOriginal: function(orignalText){
		var bookData = getBookFromOriginal(orignalText);
		this.getForm().fillData(MyUtils.toFormValues(bookData, 'book.'));
	},
	firstFocus: function(){
		this.getForm().firstFocus();
	},
	getForm: function(){
		return this.items.itemAt(0);
	}
});

/**
 * 表单中的标签面板类，每个面板都有一个textarea控件，并自动设置焦点
 */
BookFormTabPanel = top.Ext.extend(top.Ext.Panel,{
	constructor: function(title, fieldName){
		this.title = title;
		BookFormTabPanel.superclass.constructor.call(this,{
			items:[{
				xtype:"textarea",
				style: 'line-height:150%',
				name: fieldName
			}]
		});
	},
	layout:"fit",
	border: false,
	listeners:{
		activate: function(){
			this.items.itemAt(0).focus();
		}
	}
});

/**
 * 书籍原文窗口。
 * 注意：用这种方法实现继承时，items和buttons属性只能放到constructor中定义
 */
OriginalWin = top.Ext.extend(top.Ext.Window,{
    title: '书籍原文',
    width: MyUtils.getWinWidth(700),
    height: MyUtils.getWinHeight(500),
    layout: 'fit',
    plain:true,
    modal: true,
    bodyStyle:'padding:5px;',
    buttonAlign:'right',
    iconCls: 'icon-window',
	constructor: function(owner){
		this.owner = owner;
		OriginalWin.superclass.constructor.call(this, {
			items: {xtype:"textarea", emptyText:'请将有格式标记的书籍原文复制到这里'},
		    buttons: [
		        {text: '清空', handler: this.clear, scope: this},
		        {text: '查看格式', handler: this.viewFormat, scope: this},
		        {text: '确定', handler: this.ok, scope: this},
		        {text: '关闭', iconCls: 'icon-close',handler: this.close, scope: this}
		    ],
		    listeners:{
		    	show: function(){this.getField().focus(false, 300);}
		    }
		});
	},
	ok: function(){
		this.owner.fillDataFormOriginal(this.getField().getValue());
		this.close();
	},
	getField: function(){
		return this.items.itemAt(0);
	},
	viewFormat: function(){
		var format = [];
		MyUtils.each(bookMarks, function(bookMark){
			format.push(bookMark.mark);
			format.push('“' + bookMark.mark + '”的内容\n');
		});
		this.getField().setValue(format.join('\n'));
	},
	clear: function(){
		this.getField().setValue('');
		this.getField().focus();
	}
});

//导入书籍的窗口
function createImportWin(){
	var Ext = top.Ext;
	var win = new Ext.Window({
		title: '导入书籍',
	    width: MyUtils.getWinWidth(400),
	    height: MyUtils.getWinHeight(180),
	    layout: 'fit',
	    plain:true,
	    modal: true,
	    bodyStyle:'padding:1px;',
	    iconCls: 'icon-window',
	    buttonAlign:'right',
	    items: createImportForm(),
	    buttons:[
	    	{text: '确定', handler: doImport},
	    	{text: '关闭', handler: function(){win.close();}}
	    ]
	});
	
	//导入书籍
	function doImport(){
		var form = win.items.itemAt(0).getForm();
		if (MyUtils.formNotValid(form)) return;
		top.Ext.MessageBox.show({
           msg: '正在导入书籍数据，请稍候...',
           progressText: '导入中...',
           width:300,
           wait:true,
           waitConfig: {interval:200},
           icon: 'icon-download'
		});
		form.submit({
			url: 'book!import_.action',
			success: function(form, action) {
				win.close();
				var msg = action.result.data;
				msg += '<br/><br/>（如果数据不对，请检查文件内容的格式，并注意文件的编码。）';
				MyUtils.showMsg('提示', msg, 'i', function(){
					//导入成功后重新加载所有书籍数据
					bookMgr.reloadBookType(true);
				});
			}
		});
	};
	
	function createImportForm(){
		var form = new Ext.form.FormPanel({
	        baseCls: 'x-plain',
	    	border: true,
	    	bodyStyle:'padding:10px 2px',
	        labelAlign: 'right',
	        labelWidth: 60,
	        method: 'POST',
	        fileUpload: true, //注意这里
	        defaults: {anchor: '99%'},
			items: [{
				xtype: 'textfield', fieldLabel: '书籍文件',   
                name: 'upload', inputType: 'file', allowBlank: false
			},{
	            xtype: 'radiogroup',
	            fieldLabel: '文件编码',
	            columns:[60, 70, 55, 90],
	            items: [
	                {boxLabel: 'UTF-8', name: 'uploadEncoding', inputValue: 'UTF-8', checked: true},
	                {boxLabel: 'Unicode', name: 'uploadEncoding', inputValue: 'Unicode'},
	                {boxLabel: 'GBK', name: 'uploadEncoding', inputValue: 'GBK'},
	                {boxLabel: 'ISO-8859-1', name: 'uploadEncoding', inputValue: 'ISO-8859-1'}
	            ]
	        },{
		        baseCls: 'x-plain',
		        bodyStyle: 'color:#666',
	        	html: '　　<b>注意</b>：只支持文本文件，如果是word文档，请先将内容复制出来保存到txt文件中再上传，同时要注意文件编码的选择。'
	        }]
		});
		return form;
	};
	
	return win;
}

function addBook(){
	var node = bookMgr.getCurBookType();
	if (!node || node.id === 'root'){
		MyUtils.showMsg('提示', '请先选择书籍类别！', 'w');
		return;
	}
	new BookWin({title: '添加书籍'}).show();
}

function modifyBook(){
	var bookId = bookMgr.getCurBookId();
	if (bookId == 0){
		MyUtils.alert('请选择要修改的书籍！');
		return;
	}
	new BookWin({title: '修改书籍', bookId: bookId}).show();
}

function saveBook(formPanel){
	var form = formPanel.getForm();
	if (MyUtils.formNotValid(form)) return;
	MyUtils.waitSubmitting();
	form.submit({
        url:'book!save.action',
		success: function(form, action) {
			formPanel.win.close();
			bookMgr.reloadBooks();
		}
	});
}

function removeBook(){
	var ids = bookMgr.getCurBookIds();
	if (!ids){
		MyUtils.alert('请选择要删除的书籍！<br>(接住Ctrl或Shift键可多选)');
		return;
	}
	top.Ext.Msg.confirm('提示','确定要删除所选的书籍吗？<br>(删除的数据不能恢复)', function(btn){
		if (btn != 'yes') return;
		var url = "book!remove.action?ids=" + ids.join('&ids=');
		MyUtils.request(url, true, function(){
			bookMgr.reloadBooks();
		});
	});
}

/**
 * 导入书籍
 */
function importBook(){
	createImportWin().show();
}

/**
 * 修改凡例
 */
function modifyBookGuide(){
	var Ext = top.Ext;
	//保存方法
	var save = function(){
		var form = formPanel.getForm();
		if (MyUtils.formNotValid(form)) return;
    	MyUtils.waitSubmitting();
    	form.submit({
            url:'book!saveBookGuide.action',
			success: function(form, action) {
    	    	win.close();
        		MyUtils.hint("凡例已修改！");
			}
    	});
    };
    //表单
	var formPanel = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        layout: 'fit',
        items: [{
			xtype: 'textarea',
			bodyStyle: 'line-height:150%', //没起作用。。。
			name: 'bookGuide'
		}]
	});
	//窗口
	var win = new Ext.Window({
        title: '修改凡例', 
	    width: MyUtils.getWinWidth(800),
	    height: MyUtils.getWinHeight(600),
        layout: 'fit',
        plain:true, modal: true,
        bodyStyle:'padding:5px;', buttonAlign:'right', iconCls: 'icon-window',
        items: formPanel,
        listeners: {
        	show: function(){
        		MyUtils.get("book!getBookGuide.action", true, function(data){
        			var guide = formPanel.getForm().items.itemAt(0);
        			guide.setValue(data);
        			guide.focus();
        		});
        	}
        },
        buttons: [{
            text: '保存', iconCls: 'icon-save', handler: save
        },{
            text: '关闭', iconCls: 'icon-close', handler: function(){win.close();}
        }]
    });
	win.show();
}

/**
 * 分析原文，返回结构化的内容。
 * 算法简介： 逐行检查，发现标记时，记住这个标记，并处理上一次标记的内容。
 */
var bookMarks = [
	{id:'name', mark:'标题'},
 	{id:'name2', mark:'又名', filter: function(data){return data.replace(/^又名/,'').replace(/《|》/g,'');}},
 	{id:'author', mark:'作者'},
 	{id:'source', mark: '出处', filter: function(data){return data.replace(/^见/,'');}},
 	{id:'rolls', mark: '卷次'},
 	{id:'aboutAuthor', mark: '简介'},
 	{id:'abstract_', mark: '提要'},
 	{id:'academicFeatures', mark:'特点'},
 	{id:'preface', mark: '序跋'},
 	{id:'chorography', mark: '地方志'},
 	{id:'holdings', mark: '馆藏'},
 	{id:'comment', mark: '按语'}
];
function getBookFromOriginal(orignal){
	orignal = MyUtils.trim(orignal);
	if (!orignal || orignal === ""){
		return null;
	}
	var book = {}, attrId, attrValue, filter;
	var lines = orignal.split('\n');
	for (var i = 0; i < lines.length; i ++){ //遍历每一行
		var line = MyUtils.trim(lines[i]);
		if (line === '') continue;
		if (line.length < 5){ //有可能是格式标记
			var mark = line.replace(/:|：/g, '');
			var bookMark = MyUtils.findItemBySpecialAttr(bookMarks, 'mark', mark);
			if (bookMark){
				if (attrId && attrValue.length > 0){ //结束上一次找到的标记
					book[attrId] = filter ? filter(attrValue.join('\n')) : attrValue.join('\n');
				}
				//记住新的标记，并清空上一次的内容
				attrId = bookMark.id;
				filter = MyUtils.findItemBySpecialAttr(bookMarks, 'id', attrId).filter;
				attrValue = null;
				attrValue = [];
				continue;
			}
		}
		attrValue.push(line);
	}
	if (attrId && attrValue.length > 0){ //结束最后一次找到的标记
		book[attrId] = filter ? filter(attrValue.join('\n')) : attrValue.join('\n');
	}
	return book;
}